<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread></SubBread>

      <!-- 筛选区域 -->
      <SubFilter @change="queryGoods"></SubFilter>

      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序选择 -->
        <SubSort @change="sortGoods"></SubSort>

        <!-- 商品列表 -->
        <ul>
          <li v-for="i in goodsList" :key="i.id">
            <GoodsItem :goods="i" />
          </li>
        </ul>

        <!-- 下拉加载更多 -->
        <XtxPullLoad
          :finished="finished"
          :loading="loading"
          @onload="onload"
        ></XtxPullLoad>
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from './components/Sub-bread'
import SubFilter from './components/Sub-filter'
import SubSort from './components/sub-sort'
import GoodsItem from './components/Goods-item'
import { categoryGoods } from '@/api/category'
import { ref, watch } from 'vue'
export default {
  name: 'SubCategory',
  props: ['id'],
  components: { SubSort, SubFilter, SubBread, GoodsItem },
  setup (props, { emit }) {
    // 首次加载数据请求参数
    let startData = {
      categoryId: props.id,
      page: 1,
      pageSize: 15
    }

    // 是否加载完毕
    const finished = ref(false)

    // 是否正在加载
    const loading = ref(false)

    // 商品列表
    const goodsList = ref([])

    // 进入页面获取商品
    function onload () {
      loading.value = true
      categoryGoods(startData).then(res => {
        loading.value = false
        goodsList.value.push(...res.result.items)
        // 判断数据是否全部加载完
        if (goodsList.value.length >= res.result.counts) {
          finished.value = true
        }
        console.log(res)
        startData.page++
      })
    }

    // 条件筛选
    function queryGoods (data) {
      startData = { ...startData, ...data, page: 1 }
      goodsList.value = []
      finished.value = false
      loading.value = false
      onload()
    }

    // 排序筛选
    function sortGoods (data) {
      const _data = { ...data }
      if (_data.sortMethod === null) {
        _data.sortMethod = 'desc'
      }
      startData = { ...startData, ..._data, page: 1 }
      goodsList.value = []
      finished.value = false
      loading.value = false
      onload()
    }

    // watch路由切换

    watch(
      () => props.id,
      newVal => {
        console.log('改变了', newVal)
        // 清空商品列表
        goodsList.value = []
        finished.value = false
        loading.value = false
        startData = { page: 1, pageSize: 15, categoryId: newVal }
        onload()
      }
    )

    return { queryGoods, sortGoods, goodsList, onload, loading, finished }
  }
}
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
